<?php

use App\Models\KfMessage;
use App\Models\KfDialog;

class Message
{
    static $badwords = [];

    public static function loadBadWords()
    {
        static::$badwords = require_once __DIR__ . '/badwords.php';
    }

    public static function disableWordExists(&$content, $translate = false)
    {
        $pass = false;

        foreach (static::$badwords as $word)
        {
            if(strpos($content, $word) !== false)
            {
                print_r("敏感词：：：：：：".$word);
                if(!$translate) {
                    return true;
                }
                $pass = true;
                $content = str_replace($word, str_repeat('*', strlen($word)), $content);
            }
        }

        return $pass;
    }

    public static function save($dialog_id, $content, $status = 'unread', $role = 'user')
    {

        // $db = DB::instance();

        $time_now = date('Y-m-d H:i:s');
        $kf_message = [
            'dialog_id' => $dialog_id,
            'role' => $role,
            'content' => $content,
            'status' => $status,
            'created_at' => $time_now,
            'updated_at' => $time_now,
        ];


        KfMessage::create($kf_message);

        // $db->insert('yy_kf_message')->cols($kf_message)->query();
    }

    public static function saveBannedMessage($dialog_id, $content)
    {
        static::save($dialog_id, $content, 'banned');
    }


    public static function sendToUser($url, $message)
    {
        // print_r($url);
        // print_r($message);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
        $data = curl_exec($ch);
        if($errno = curl_errno($ch)) {
            $error_message = curl_strerror($errno);
            echo "cURL error ({$errno}):\n {$error_message}";
        }
        curl_close($ch);
        // var_dump($data);
    }

}